package com.manger.format;

import com.manger.common.office.sax.ExcelFactory;
import com.manger.model.Project;
import com.manger.model.XingFei;
import com.manger.utils.CopyFiles;
import com.manger.utils.DetNameEnum;
import com.manger.utils.LoanFileEnum;
import com.manger.utils.SystemConstant;
import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *@ClassName XFPayCaseFilesFormat
 *@Description  TODO
 *@Author @LiuHongJun
 *@Date 2025/9/1 16:01
 *@Version 1.0
 */
public class XFPayCaseFilesFormat implements CaseFilesFormat{

    private static Map<String, LoanFileEnum> filesMapping = new HashMap<>();

    private List<String> onlyOneFileNameMarks = new ArrayList<>();

    private static String ocrIdCardMark = "被告身份证";

    private static String hasDanBaoMark = "天津信飞融资担保有限公司";

    private Map<String, String> idCardMap = new HashMap<>();

    private Map<String,String> zzMap = new HashMap<>();

    private Map<String,List<XFZJF>> nameMap = new HashMap<>();

    {
        //  filesMapping.put("被告身份证", LoanFileEnum.PART_IDENTITY_CERTIFICATE);
        onlyOneFileNameMarks.add("人脸识别照");
        onlyOneFileNameMarks.add("身份证人像面");
        onlyOneFileNameMarks.add("身份证国徽面");
    }

    @Override
    public void format(String extractDir, String targetDir, Project project) throws Exception {
        System.out.println("++++++++++++++++++++++信飞案件数据整理+++++++++++++++++++++++++++++");
        List<String> ignoreFileList = project.getIgnoreFilesList();
        List<String> ignoreDirList = project.getIgnoreDirList();
        String excelFilePath = extractDir + "/" + SystemConstant.ENTRUSTED_INFO;
        Map<String,List<?>> map = ExcelFactory.getExcelFactory().getParseExecutor().parse(new File(excelFilePath), XingFei.class).get();
        if(map.keySet().size() <= 0){
            System.out.println("没有解析到委托信息表数据！");
            return;
        }
        List<XingFei> xingFeiList = (List<XingFei>) map.get(map.keySet().iterator().next());
        if(xingFeiList == null){
            System.out.println("没有解析到委托信息表数据！");
            return;
        }
        List<XingFei> errorList = new ArrayList<>();
        String zzFileDir = extractDir + "/" + project.getDebtName() + "/" + "资质材料";
        File zzFile = new File(zzFileDir);
        if(zzFile.exists()){
            File[] files = zzFile.listFiles();
            for(File file : files){
                File[] tempFiles = file.listFiles();
                for(File tempFile : tempFiles){
                    zzMap.put(tempFile.getName(),tempFile.getAbsolutePath());
                }
            }
        }

        for(XingFei fei: xingFeiList){
            if (StringUtils.isEmpty(fei.getIdCard())){
                errorList.add(fei);
                continue;
            }
            String dirName = fei.getOrderId();
            String resourcePath = extractDir + "/" + project.getDebtName() + "/" + dirName;
            String tempTargetDir = targetDir + "/" + project.getDebtName() + "/" + SystemConstant.CASE_FILE_DIR_NAME
                    + "/" + fei.getLoanUserName() + "-" + fei.getIdCard();

            try{
                File file = new File(resourcePath);
                if(!file.exists()){
                    continue;
                }
                CopyFiles.createDirs(tempTargetDir);
                File[] tempFiles = file.listFiles();
                for(File tempFile : tempFiles){
                    if (tempFile.isFile() && CopyFiles.hasFileNameMark(tempFile.getName(), ignoreFileList)) {
                        continue;
                    }
                    if (tempFile.isDirectory() && CopyFiles.hasFileNameMark(tempFile.getName(), ignoreDirList)) {
                        continue;
                    }
                    String targetRealPath = tempTargetDir + "/" + CopyFiles.getLoanFileEnum(tempFile.getName(),filesMapping).getName();
                    if (!CopyFiles.checkHasCopyFileToDirByOnlyOneFileNameMarks(tempFile.getName(), onlyOneFileNameMarks,targetRealPath)) {
                        continue;
                    }
                    CopyFiles.copyFileToDir(tempFile.getAbsolutePath(),targetRealPath );
                    idCardMap.put(fei.getIdCard(),tempTargetDir);
                }
                //拷贝统一数据
               // CopyFiles.copyBaseFiles(tempTargetDir, project);
                String nameMapKey = fei.getLoanUserName() + "-" + fei.getIdCard();
                List<XFZJF> xfzjfList = nameMap.get(nameMapKey);
                xfzjfList = xfzjfList == null ? new ArrayList<>() : xfzjfList;
                boolean hasExist = false;
                for(XFZJF xfzjf: xfzjfList){
                    if(fei.getZjf().equals(xfzjf.name)){
                        xfzjf.setNum(xfzjf.getNum() + 1);
                        hasExist = true;
                    }
                }
                if(!hasExist){
                    XFZJF xfzjf = new XFZJF();
                    xfzjf.setNum(1);
                    xfzjf.setName(fei.getDbzt());
                    xfzjfList.add(xfzjf);
                }
                nameMap.put(nameMapKey,xfzjfList);
                boolean mark = false;
                //拷贝资质文件
                for(String key:zzMap.keySet()){
                    if(key.contains(fei.getZjf())){
                        //拷贝资质到证据目录
                        String tempZZDir = tempTargetDir + "/" + LoanFileEnum.EVIDENCE_MATERIALS.getName() + "/";
                        CopyFiles.copyFileToDir(zzMap.get(key),tempZZDir);
                        mark = true;
                    }
                }
                if(!mark){
                    errorList.add(fei);
                }

                System.out.println("整理原始数据成功：【" + dirName + "】");
            }catch (Exception e){
                e.printStackTrace();
                errorList.add(fei);
                System.out.println("整理原始数据失败：【" + dirName + "】");
            }
        }

        //证据目录(无反担保）,证据目录(有反担保）
        //拷贝统一数据
        for(String key: nameMap.keySet()){
            List<XFZJF> xfzjfList = nameMap.get(key);
            String tempTargetDir = targetDir + "/" + project.getDebtName() + "/" + SystemConstant.CASE_FILE_DIR_NAME
                    + "/" + key;
            File file = new File(SystemConstant.getConfigDir() + "/" + project.getDebtName());
            if(!file.exists()){
                return;
            }
            String danBaoFileName = ignoreDanBaoFileNameMark(xfzjfList);

            File[] files = file.listFiles();
            for(File fileDir : files){
                File[] tempFiles = fileDir.listFiles();
                for(File tempFile : tempFiles){
                    if(tempFile.getName().contains(danBaoFileName)){
                        continue;
                    }
                    String targetPath = tempTargetDir + File.separator + fileDir.getName() + File.separator + tempFile.getName();
                    File tempFileConfig = new File(targetPath);
                    if(tempFileConfig.exists()){
                        continue;
                    }
                    if(!tempFileConfig.getParentFile().exists()){
                        tempFileConfig.getParentFile().mkdirs();
                    }
                    Files.copy(Paths.get(tempFile.getAbsolutePath()),Paths.get(targetPath));
                }
            }
        }

        //处理数据u idCardMap : 身份证：地址
        CopyFiles.copyOtherMaterialFileToDir(extractDir,idCardMap);

        if(!errorList.isEmpty()){
            String errorFilePath = targetDir + "/" + project.getDebtName() + "/" + SystemConstant.ERROR_EXCEL_PRE + System.currentTimeMillis() + ".xlsx";
            ExcelFactory.getExcelFactory().getExportExecutor().sheet("整理错误")
                    .data(errorList).head(XingFei.class).write(new FileOutputStream(errorFilePath));
            System.out.println("导出整理错误数据【"+errorFilePath+"】");
        }
    }

    //证据目录(无反担保）,证据目录(有反担保）
    //当前人只有一条：天津信飞融资担保有限公司 : 无反担保
    private String ignoreDanBaoFileNameMark(List<XFZJF> xfzjfList){
        if(xfzjfList.size() != 1){
            return "无反担保";
        }
        if(!"天津信飞融资担保有限公司".equals(xfzjfList.get(0).getName())){
            return "无反担保";
        }
        return "有反担保";
    }

    class XFZJF{
        private String name;

        private Integer num;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getNum() {
            return num;
        }

        public void setNum(Integer num) {
            this.num = num;
        }
    }

    public static void main(String[] args) throws Exception{
        String extractDir = "D:\\workSpace\\AutomaticCase\\format\\1756714714644\\信飞";
        String targetDir = "D:\\workSpace\\AutomaticCase\\format\\target\\123456";
        Project project = new Project();
        project.setDebtName(DetNameEnum.XF.getDesc());
        XFPayCaseFilesFormat threeSixZeroCaseFilesFormat = new XFPayCaseFilesFormat();
        threeSixZeroCaseFilesFormat.format(extractDir,targetDir,project);
    }
}
